package com.suray.system.run.license;

import com.alibaba.fastjson.JSON;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.utils.HttpStatus;
import com.suray.commin.core.utils.ServletUtils;
import com.suray.commin.core.utils.SpringContextHolder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LicenseCheckInterceptor
 *
 * @author
 * @date 2018/4/25
 * @since 1.0.0
 */
public class LicenseCheckInterceptor extends HandlerInterceptorAdapter {

    private LicenseCheckListener licenseCheckListener = SpringContextHolder.getBean(LicenseCheckListener.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LicenseVerify licenseVerify = new LicenseVerify();
        //校验证书是否有效
        boolean verifyResult = licenseVerify.verify();
        if (verifyResult) {
            return true;
        } else {
            //更新证书
            licenseCheckListener.refreshLicense();
            if (licenseVerify.verify()) {
                return true;
            } else {
                ServletUtils.renderString(response, JSON.toJSONString(ResponseData.error(HttpStatus.LICENSE_OUT_TIME, "您的证书无效，请核查服务器是否取得授权或重新申请证书！")));
                return false;
            }
        }
    }

}
